package com.exp.irorichat.exception;


import com.exp.irorichat.result.Result;
import lombok.extern.slf4j.Slf4j;
import org.springframework.http.HttpStatus;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.ResponseStatus;

import java.io.IOException;
import java.util.HashMap;
import java.util.Map;


@ControllerAdvice
@Slf4j
public class GlobalExceptionHandler {

    /**
     * 处理所有异常
     * @param e
     * @return
     */
    @ExceptionHandler(Exception.class)
    @ResponseBody
    public Result error(Exception e) {
        log.error("全局异常出现问题{},异常类型{}",e.getMessage(),e.getClass());
        e.printStackTrace();
        return Result.fail().message("请稍后重试或联系系统管理人员...");
    }


    //自定义异常处理

    /**
     * 处理自定义异常
     * @param e
     * @return
     */
    @ExceptionHandler(GlobalException.class)
    @ResponseBody
    public Result error(GlobalException e) {
        log.error("自定义异常出现问题{},异常类型{}",e.getMessage(),e.getClass());
        e.printStackTrace();
        return Result.fail().code(e.getCode()).message(e.getMsg());
    }



    /**
     * 处理IO异常
     * @param e
     * @return
     */
    @ExceptionHandler(IOException.class)
    @ResponseBody
    public Result error(IOException e) {
        log.error("IO出现问题{},异常类型{}",e.getMessage(),e.getClass());
        e.printStackTrace();
        return Result.fail().message("导入Excel表格异常,请检查Excel表格字段");
    }

    /**
     * 处理数据校验异常
     * @param e
     * @return
     */
    @ExceptionHandler(MethodArgumentNotValidException.class)
    @ResponseBody
    public Result handleValidException(MethodArgumentNotValidException e) {
        log.error("数据效验出现问题{},异常类型{}",e.getMessage(),e.getClass());
        BindingResult bindingResult = e.getBindingResult();
        Map<String,String> errMap = new HashMap<>();
        bindingResult.getFieldErrors().forEach((fieldError) -> {
            errMap.put(fieldError.getField(),fieldError.getDefaultMessage());
        });
        return Result.fail(errMap);
    }

}
